/**
 * 
 */
package tk.sunlatus.project.dbmanage;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.springframework.util.DefaultPropertiesPersister;

import tk.sunlatus.project.common.constants.SunlatusConstants.SysConstant;
import tk.sunlatus.project.config.ConfigurationManager;
import tk.sunlatus.project.security.CfgPasswordEncoder;

/**
 * @author sunlotus 定制xml加载类，以支持密码加密功能
 */
public class SunlotusPropertiesPersister extends DefaultPropertiesPersister {
    // private static final Logger LOGGER =
    // Logger.getLogger(SunlotusPropertiesPersister.class);
    private ConfigurationManager configurationManager = null;
    private CfgPasswordEncoder cfgPasswordEncoder = null;

    @Override
    public void loadFromXml(Properties props, InputStream is) throws IOException {
        // TODO Auto-generated method stub
        XMLConfiguration config = new XMLConfiguration();
        try {
            config.load(is);
            Iterator<?> keyIt = config.getKeys();
            String key = null;
            String value = null;
            while (keyIt.hasNext()) {
                key = (String) keyIt.next();
                value = config.getString(key);
                props.put(key, decodePassword(key, value));
            }

        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    private String decodePassword(String key, String pwd) {
        if (!key.endsWith("password")) {
            return pwd;
        }

        Configuration config = configurationManager.getCfgNoRefresh().get(SysConstant.SYS_CONFIG_NOREFRESH_KEY);
        String password = config.getString(SysConstant.PASSWORD);
        pwd = cfgPasswordEncoder.decrypt(pwd, password, null);
        return pwd;
    }

    public ConfigurationManager getConfigurationManager() {
        return configurationManager;
    }

    public void setConfigurationManager(ConfigurationManager configurationManager) {
        this.configurationManager = configurationManager;
    }

    /**
     * @return the cfgPasswordEncoder
     */
    public CfgPasswordEncoder getCfgPasswordEncoder() {
        return cfgPasswordEncoder;
    }

    /**
     * @param cfgPasswordEncoder
     *            the cfgPasswordEncoder to set
     */
    public void setCfgPasswordEncoder(CfgPasswordEncoder cfgPasswordEncoder) {
        this.cfgPasswordEncoder = cfgPasswordEncoder;
    }

}
